const db = uniCloud.database();
const dbCmd = db.command;
const $ = db.command.aggregate;
module.exports = async function(options = {}) {
	const { category, characterId } = options;
	const token = this.getUniIdToken();
	if (!token || !category || !characterId) {
		throw new Error('非法访问');
	}
	let userChapter = [];
	let [courseList, courseListCustom] = await Promise.all([
		db.collection('a-dz-course-list')
		.aggregate()
		.match({
			category
		})
		.lookup({
			from: 'a-dz-complete-list',
			let: {
				mainid: '$courseId'
			},
			pipeline: $.pipeline().match(dbCmd.expr($.and([
					$.eq(['$courseId', '$$mainid']),
					$.eq(['$characterId', characterId])
				])))
				.project({
					_id: 0,
					createTime: 1,
					rating: 1
				})
				.done(),
			as: 'complete'
		})
		.project({
			_id: 0,
			icon: 0
		})
		.end(),
		// 获取自定义的课程
		db.collection('a-dz-course-list-custom')
		.aggregate()
		.match({
			category
		})
		.lookup({
			from: 'a-dz-complete-list-custom',
			let: {
				mainid: '$courseId'
			},
			pipeline: $.pipeline().match(dbCmd.expr($.and([
					$.eq(['$courseId', '$$mainid']),
					$.eq(['$characterId', characterId])
				])))
				.project({
					_id: 0,
					createTime: 1,
					rating: 1
				})
				.done(),
			as: 'complete'
		})
		.project({
			_id: 0,
			icon: 0
		})
		.end()
	])

	return {
		code: 0,
		data: courseList.data.concat(courseListCustom.data),
		msg: '获取成功'
	}
}